import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '../router'
import { loginApi, logoutApi } from '../api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  
  // 登录方法
  const login = async (loginData) => {
    try {
      
      const res = await loginApi(loginData)
      console.log('%c [ res ]-15', 'font-size:18px; background:#9444d4; color:#d888ff;', res)
      token.value = res.data.token
      userInfo.value = {}
      
      // 保存到localStorage
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('userInfo', JSON.stringify({}))
      router.push('/home')
      return true
    } catch (error) {
      return false
    }
  }
  
  // 登出方法
  const logout = async () => {
    try {
      await logoutApi()
    } finally {
      // 清除本地存储
      token.value = ''
      userInfo.value = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      
      // 跳转到登录页
      router.push('/login')
    }
  }
  
  return {
    token,
    userInfo,
    login,
    logout
  }
})